﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using Pg.BioMedics.SDR.Services;

namespace Pg.BioMedics.SDR.Web.Modules
{
    /// <summary>
    /// A HTTP module responsoble for loading data caches
    /// </summary>
    public class CacheLoaderModule : IHttpModule
    {
        #region Event handlers

        private void OnBeginRequest(object sender, EventArgs e)
        {
            if (!ServiceFactory.CacheManagementService.IsInitialized())
            {
                HttpApplication app = (HttpApplication)sender;

                app.Response.StatusCode = 503;
                app.Response.StatusDescription = "Data sources initialization...";
                app.Response.Write("503 Service Unavailable");

                app.CompleteRequest();
            }
        }

        #endregion

        #region IHttpModule Members

        public void Init(HttpApplication context)
        {
            // assign event handlers
            context.BeginRequest += new EventHandler(OnBeginRequest);

            // load caches
            ServiceFactory.CacheManagementService.Fill();
        }        

        /// <summary>
        /// Dispose module resources - mainly clear caches
        /// </summary>
        public void Dispose()
        {
            ServiceFactory.CacheManagementService.Clear();
        }

        #endregion
    }
}
